;var Utils=function($){

function toLoginPage() {
	console.log('跳转登录页。。。。。。。。。。。')
    window.location.href='/login.html';
}
//弹出消息窗体
function alert(title,message,callback){
		var $modal = $('<div class="modal fade in" tabindex="-1" data-backdrop="static" data-keyboard="false"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button><h4 class="modal-title">'+title+'</h4></div><div class="modal-body" style="text-align: center;font-size: 33px;">'+message+'</div><div class="modal-footer"><button type="button" data-dismiss="modal" class="btn dark btn-outline cancel">取消</button><button type="button" data-dismiss="modal" class="btn green sure">确定</button></div></div></div></div>').appendTo('body');
		$modal.modal('show');
		var r=false;
		$('.sure',$modal).on('click',function(){r=true;});
		$modal.on('hide.bs.modal',function(){
			if(callback && typeof callback ==='function')callback(r,$modal);
			$(this).remove();
		});
}

//定时前进  进度条
var timer=null;
function progress(op){
	if('close' == op){
		if(timer)window.clearInterval(timer);
		$("div.progressModal:last").modal('hide');
	}else{
		var $progress = $('<div class="modal progressModal fade in" tabindex="-1" data-backdrop="static" data-keyboard="false"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"></div><div class="modal-body"><div class="progress"><div class="progress-bar progress-bar-success progress-bar-striped active"></div><div class="progress-bar progress-bar-warning progress-bar-striped active"></div><div class="progress-bar progress-bar-danger progress-bar-striped active"></div></div></div></div></div></div>').appendTo('body');
		var $1=$('div.progress-bar:first',$progress),$2=$('div.progress-bar:eq(1)',$progress),$3=$('div.progress-bar:last',$progress);
		var width=0;
		timer = window.setInterval(function(){
			if(width >= 99){$('div.progress-bar',$progress).css('width','0%');}
			width = width >= 100 ? 0 : width;
			if(33 >= width ){
				$1.css('width',width+'%');
			}else if(66 >= width ){
				$2.css('width',width-33+'%');
			}else if(99 >= width ){
				$3.css('width',width-66+'%');
			}
			width = width + 3;
		},550);
		$progress.modal('show');
		$progress.on('hide.bs.modal',function(){$(this).remove();});
	}
}
//进度条
function stepProgress(options){
	if(options instanceof Array){
		var stepSize = options.length,colSize = 12/stepSize;
		var progressHtml = '',stepNameHtml = '';
		for(var i=0;i<options.length;i++){
			stepNameHtml += '<div class="col-md-'+colSize+'">'+options[i]+'</div>';
			progressHtml +='<div class="progress-bar progress-bar-success progress-bar-striped active"></div>';
		}
		var progressModelHtml = '<div class="modal progressModal fade in" tabindex="-1" data-backdrop="static" data-keyboard="false">'+
									'<div class="modal-dialog"><div class="modal-content"><div class="modal-header"></div>'+
									'<div class="modal-body"><div class="row">'+stepNameHtml+'</div><div class="progress">'+progressHtml+
									'</div></div></div></div></div>';
		var $progress = $(progressModelHtml).appendTo('body');
		$('div.progress-bar:first',$progress).css('width',100/stepSize+'%');
		$progress.modal('show');
		$progress.on('hide.bs.modal',function(){$(this).remove();});
	}else if((typeof options == 'number') && options.constructor==Number){//set progress step
		var $progress = $("div.progressModal:last"),$step=$('div.progress-bar:eq('+options+')',$progress);
		var stepSize = $step.siblings().length;
		$step.css('width',100/stepSize+'%');
		if(stepSize-1 == options){
			$("div.progressModal:last").modal('hide');
		}
	}else{
		$("div.progressModal:last").modal('hide');
	}
}
function showTempModal($temp,fun){
		$("body").append($temp.prop("outerHTML"));
		var $modal = $("div.modal:last");
		if(fun && typeof fun === 'function')fun($modal,$);
		$modal.on('hide.bs.modal',function(){$(this).remove();});
		$modal.modal('show');
}
function showRemote(option,fun){
	var modal ='<div class="modal fade in" tabindex="-1" data-backdrop="static" data-keyboard="false"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button><h4 class="modal-title"></h4></div><div class="modal-body">'+
			'<div class="block-spinner-bar"><div class="bounce1"></div><div class="bounce2"></div><div class="bounce3"></div></div>'+
			'</div><div class="modal-footer"><button type="button" data-dismiss="modal" class="btn dark btn-outline cancel">取消</button><button type="button" class="btn green sure">确定</button></div></div></div></div>';
	$("body").append(modal);
	var $modal = $("div.modal:last");
	if(option.width)$('div.modal-dialog',$modal).css({width:option.width+'px'});
	if(option.height)$('div.modal-body',$modal).css({height:option.height+'px'});
	if(option.title)$('h4.modal-title',$modal).text(option.title);
	$modal.on('hide.bs.modal',function(){$(this).remove();});
	$.ajax({
        url:option.url,
        type:'GET',
        dataType:'html',
        success:function(data){
		    $('div.block-spinner-bar',$modal).remove();
		    $('div.modal-body',$modal).html(data);
            if(fun && typeof fun === 'function')fun($("div.modal:last"));
	    }
	});
	$modal.modal('show');
}

//获取指定区域的参数
function getParams($area){
		var params={};
		$('input,select',$area).each(function(){var key=$(this).attr('name');if(key)params[key]=$(this).val();});
		return params;
}
//设置参数到指定区域
function setParams($area,params,noSet){
	$('input',$area).each(function(){
		var key=$(this).attr('name'),value=params[key];
		if(key && value && !contains(key,noSet))$(this).val(value);
		});
	$('select',$area).each(function(){
		var key=$(this).attr('name'),value=params[key];
		if(key && value && !contains(key,noSet)){
			$.grep($('option',this),function(node,index){
				if(value == $(node).attr('value'))$(node).attr('selected',true);
				else $(node).attr('selected',false);
			});
		}
	});
}

function contains(value,arr){
	if(!arr || arr.length == 0)return false;
	for(var i=0;i<arr.length;i++){
		if(arr[i]==value)return true;
	}
	return false;
}

/**
 * 预览图片ajax上传图片
1.required bootstrap-fileinput.js
2.html like this:                                
        <div class="fileinput fileinput-new" data-provides="fileinput">
            <div class="fileinput-preview thumbnail" data-trigger="fileinput" style="width: 200px; height: 150px;"></div>
			<div class="progress" style="margin-top:-5px;">
					<div class="progress-bar progress-bar-success" style="width: 0%"><span class="percent">0%</span></div>
			</div>
            <div style="margin-top:-18px;">
                    <span class="btn red btn-outline btn-file">
                          <span class="fileinput-new"> 选择 </span>
                          <span class="fileinput-exists"> 更改 </span>
						  <input type="file" id="singleFile">						 
					</span>
					<a onclick="upload()" class="btn red fileinput-exists">上传</a>
                    <a href="javascript:;" class="btn red fileinput-exists" data-dismiss="fileinput"> 删除 </a>
             </div>
        </div>
3.configed options: 	  		
   			var options={
	  			url:"http://127.0.0.1:8080/testupload",
	  			//data:{name:'张学友的图片'},
	  			progress:{bar:$('.progress-bar'),percent:$('.percent')},//进度条
	  			success:function(data){alert(data);}
	  		};
	  		$('#singleFile').ajaxImgUpload(options);      
 */
function initBootstrapFileinput(){
	$.fn.ajaxImgUpload=function(options){
		if($(this).is('input') && 'file' == $(this).attr('type')){
			var fileObj = $(this).get(0).files[0];// 获取文件对象
		    var form = new FormData();
		        for(var key in options.data){// 可以增加表单数据
		        	form.append(key,options.data[key]);    
		        }
		        form.append("file", fileObj);// 文件对象
		    var xhr = new XMLHttpRequest();
		        xhr.open("post",options.url, true);
		        if(options.progress){//是否显示进度条
			            xhr.upload.addEventListener('progress', function(event) {
			                       var percent = 0;
			                       var position = event.loaded || event.position; 
			                       var total = event.total;
			                       if (event.lengthComputable) {
			                           percent = Math.ceil(position / total * 100);
			                       }
			                    		var percentVal = percent + '%';
			                       options.progress.bar.width(percentVal);
			                       options.progress.percent.html(percentVal);
			            }, false);
		        }
				if(options.beforeSend && typeof options.beforeSend === 'function'){
					options.beforeSend(xhr);
				}
		        xhr.send(form);
		        xhr.onreadystatechange=function(){
		       	 if(xhr.status == 200 && xhr.readyState==4){
		    	         var data = xhr.responseText;    
		    	         options.success(data,xhr);
		       	 }
		        };
		}else throw new Error('not a file input element!');
	};
}
//权限 访问时携带access_token 错误处理handler
function initPermission(){
	var _ajax = $.ajax;
	$.ajax = function(opt){
	 		var _opt = {
						headers: {token: $.cookie('token')},
						dataFilter: function(data,type,xhr){
							if(data == 'TO_LOGIN')toLoginPage();
							else if(data == 'NOPERMISSION')alert('警告','你没有权限操作!');
							else return data;
						},
						error:function(xhr,statusText,thrownEx){
							if(403 == xhr.status || 401 == xhr.status){
								var ct = xhr.getResponseHeader("content-type") || "";
								if (ct.indexOf('application/xml') > -1) {
									var xml = $.parseXML(xhr.responseText);
									if('invalid_token' === xml.querySelector('error').innerHTML){
										toLoginPage();
									}
									alert('警告',xml.querySelector('error_description').innerHTML);
								}
							}
							if(typeof opt.error === 'function')opt.error(xhr,statusText,thrownEx);
							if(statusText=='timeout'){alert('警告提示','请求超时!');}
							if(statusText=='error' && xhr.status == 500){alert('警告提示','后台异常!');}
						}
	 		};
	 		var options = $.extend(true,{}, opt,_opt);
	 		return _ajax(options);
	};
}

//获取cookie值
function cookie(key){
		var arr = document.cookie.split("; ");
		for(var i = 0;i < arr.length;i ++){
			var temp = arr[i].split("=");
			if(temp[0] == key){
				return temp[1];
			}
		}
		return false;
}

//修改密码
function handleUpdatePwd(){
	var $modal = $('#updatePWD');
	$modal.modal('show');
}
function initCheckValidate(){
	var $modal = $('#updatePWD');
	$('.sure',$modal).click(function(){
		if($('form',$modal).valid()){
			$.ajax({url:'/admin/api?service=user.updatepwd',type:'POST',data:getParams($modal),
				success:function(data){if(data)alert('操作成功','修改密码成功!');else alert('操作失败','密码错误!');}});
		}
	});
	var checkRules = {rules: {
							old_pwd:{
								required: true,
								vd_azAZ09:[6,20]
							},
							new_pwd:{
								required: true,
								vd_azAZ09:[6,20]
							},
							re_new_pwd:{
								required: true,
								equalTo: "#updatePWD .form-control:eq(1)"
							},
						}};
	$('form',$modal).validate(checkRules);
}

var stompClient=null;
function initWebSocket(subscribeUri){
	 $.when($.getScript("/webjars/sockjs-client/1.1.2/sockjs.min.js"),
			$.getScript("/webjars/stomp-websocket/2.3.3/stomp.min.js")).done(function(){
				var ws = new SockJS('/hello',undefined, {protocols_whitelist:['websocket']});
	            stompClient = Stomp.over(ws);
	            stompClient.debug=false;
	            stompClient.connect({},function(frame){
	                stompClient.subscribe(subscribeUri,function(data){
	                		var body = JSON.parse(data.body);
	                		webSocketMessage(body);
	                	});
	            },null);
       });
}
function webSocketSend(url,headers,params){
	if(stompClient)stompClient.send(url,headers,JSON.stringify(params));
}
//websocket消息解析
var webSocketMessageListener={};
function webSocketMessage(body){
	if(body.processDefinitionKey){
		addHeadTask(body);
	}else if(body.msgType &&  'user.permission.refreshToken' === body.msgType){// permission user right updated msg
		var date = new Date();
		date.setTime(date.getTime() + (2 * 60 * 60 * 1000));
		$.cookie('access_token',body.new_token,{expires:date,path:'/'});
		window.location.reload();
	}
	for(var key in webSocketMessageListener){
		webSocketMessageListener[key](body);
	}
}

//添加头部消息提醒
function addHeadTask(json){
	var formatName = {LendMoney:"借款流程审批",flow_leave:"请假流程审批"};
	var html = '<li task-id="'+json.id+'"><a href="#"><span class="label label-sm label-icon label-success"><i class="fa fa-bell-o"/></span>'+formatName[json.processDefinitionKey]+'<span class="time">'+json.name+'</span></a></li>';
	$taskLi=$('li.task-dropdown'),
	$taskNum=$('a span.badge',$taskLi),
	$taskContener=$('ul.dropdown-menu-list',$taskLi),
	taskNum = parseInt($taskNum.text());
	if(0 == taskNum)$taskContener.html(html);
	else $taskContener.append(html);
	$('ul.dropdown-menu-list>li:last',$taskLi).click(function(){handleHeadTask();});
	$taskNum.text(taskNum+1);
}
//移除头部消息提醒
function removeHeadTask(taskId){
	$taskLi=$('li.task-dropdown'),
	$taskNum=$('a span.badge',$taskLi),
	$taskContener=$('ul.dropdown-menu-list',$taskLi),
	taskNum = parseInt($taskNum.text());
	$('li[task-id="'+taskId+'"]',$taskContener).remove();
	taskNum = taskNum-1;
	taskNum = taskNum < 0 ? 0 : taskNum;
	$taskNum.text(taskNum);
	if(taskNum == 0)$taskContener.html('<li><span class="label label-sm label-icon label-success"><i class="fa fa-bell-o"/></span>你没有消息！</span></li>');
}
//点击头部消息提醒
function handleHeadTask(){
	$('a.ajaxify[href="/admin/api?service=process.task.table"]').click();
}
function init(){
	initPermission();			//$.ajax  dataFilter
	initBootstrapFileinput();	//BootstrapFileinput
	
	
	initCheckValidate();									  //修改密码  绑定表单事件 表单校验
	$('#UpdatePwd_btn').click(function(){handleUpdatePwd();});//修改密码
	$('span.username').text($.cookie('realName'));
	$('li.task-dropdown').find('ul.dropdown-menu-list>li>a').click(function(){handleHeadTask();});
	$('li.task-dropdown').find('div.slimScrollDiv').slimScroll({height: '250px'});
}
init();
return {getParams:getParams,
	    setParams:setParams,
	    alert    :alert,						    	   	   //弹出 消息窗
	    progress :progress,									   //进度条
	    stepProgress :stepProgress,							   //进度条
		show	 :showTempModal,							   //弹出  模板窗体
		showRemote:showRemote,								   //弹出  远程内容窗体
		initSocket:initWebSocket,
		socketSend:webSocketSend,
		webSocketMessageListener:webSocketMessageListener,
	    };
}(window.jQuery);